﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Marbles.Core.Content.Pages;
using Marbles.Core.Content.SiteMap;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:Ticker runat=server></{0}:Ticker>")]
    public class Ticker : WebControl
    {

        public string Text { get { object obj = ViewState["Text"]; return (obj == null) ? "" : obj.ToString(); } set { ViewState["Text"] = value; } }
        public string ParentPageName { get { object obj = ViewState["ParentPageId"]; return (obj == null) ? "" : obj.ToString(); } set { ViewState["ParentPageId"] = value; } }
        internal Marbles.Core.Pages.Page CurrentPage { get { return ((Marbles.Core.Pages.Page)this.Page); } }
        internal PageDefinition ParentPage { get { return new PageDefinition(this.CurrentPage.CurrentWeb.SiteName, ParentPageName); } }
        internal Marbles.Core.Content.SiteMap.WebSiteMap SiteMap { get { return new Content.SiteMap.WebSiteMap(ParentPage, true); } }

        private const string resourceKey = "Marbles.Resources.Scripts.jQuery.jquery.li-scroller.1.0.js";

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!Page.ClientScript.IsClientScriptIncludeRegistered("Ticker"))
            {
                Page.ClientScript.RegisterClientScriptInclude("Ticker", Marbles.Resources.ResourceHandler.GetWebResourceUrl(Page, resourceKey));
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.AddAttribute("id", this.ClientID);
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);

            foreach (WebSiteMapNode node in this.SiteMap)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write(node.PublishDate.ToLongDateString());
                writer.RenderEndTag();
                writer.AddAttribute("href", node.LocalUrl);
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write(node.Title);
                writer.RenderEndTag();
                writer.RenderEndTag();
                writer.WriteLine();
            }

            writer.RenderEndTag();

            writer.AddAttribute("type", "text/javascript");
            writer.AddAttribute("language", "javascript");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.WriteLine("$(function(){");
            writer.Write("$(\"ul#" + this.ClientID + "\").liScroll(");

            writer.WriteLine(")");
            writer.WriteLine("});");
            writer.RenderEndTag();
        }
    }
}
